package com.meirengu.webview.service.impl;

import com.meirengu.service.impl.BaseServiceImpl;
import com.meirengu.webview.common.UserChannelEnum;
import com.meirengu.webview.dao.KwStatisticInterfaceDao;
import com.meirengu.webview.model.KwInterfaceConfig;
import com.meirengu.webview.model.KwStatisticInterface;
import com.meirengu.webview.model.KwStatisticInterfaceMonth;
import com.meirengu.webview.service.KwInterfaceConfigService;
import com.meirengu.webview.service.KwInterfaceLimitService;
import com.meirengu.webview.service.KwStatisticInterfaceMonthService;
import com.meirengu.webview.service.KwStatisticInterfaceService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * KwStatisticInterface服务实现层
 *
 * @author Liu
 * @create Wed Sep 05 16:27:51 CST 2018
 */
@Service
public class KwStatisticInterfaceServiceImpl extends BaseServiceImpl<KwStatisticInterface> implements KwStatisticInterfaceService {


    @Autowired
    private KwStatisticInterfaceDao kwStatisticInterfaceDao;
    @Autowired
    private KwStatisticInterfaceService kwStatisticInterfaceService;
    @Autowired
    private KwInterfaceConfigService kwInterfaceConfigService;
    @Autowired
    private KwInterfaceLimitService kwInterfaceLimitService;
    @Autowired
    private KwStatisticInterfaceMonthService kwStatisticInterfaceMonthService;

    Logger logger = LoggerFactory.getLogger(KwStatisticInterfaceServiceImpl.class);

    public List<Map<String, Object>> getFilterNum(Map map) {
        return kwStatisticInterfaceDao.getFilterNum(map);
    }

    @Override
    public List<Map<String, Object>> getReasonFilter(Map map) {
        return kwStatisticInterfaceDao.getReasonFilter(map);
    }

    @Override
    public Integer getRefusNumPush(Map map) {
        return kwStatisticInterfaceDao.getRefusNumPush(map);
    }

    @Override
    public Integer getNumPush(Map map) {
        return kwStatisticInterfaceDao.getNumPush(map);
    }

    @Override
    public List<Map<String, Object>> getReasonPush(Map map) {
        return kwStatisticInterfaceDao.getReasonPush(map);
    }

    @Override
    public synchronized void statisInterface() throws Exception {

        Map<String, String> filterMap = new HashMap<>();
        Map<String, String> limitMap = new HashMap<>();
        Map<String, String> pushMap = new HashMap<>();
        Map<String, String> dataMap = new HashMap<>();
        Map<String, String> map = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date currentDate = new Date();
        Date dayBeginTime = com.meirengu.utils.DateUtils.getDayBeginTime(currentDate);
        //当天结束时间
        Date dayEndTime = com.meirengu.utils.DateUtils.getDayEndTime(currentDate);
        Date TimeBegin = org.apache.commons.lang3.time.DateUtils.addDays(dayBeginTime, -1);
        Date TimeEnd = org.apache.commons.lang3.time.DateUtils.addDays(dayEndTime, -1);
        String createTimeBegin = sdf.format(TimeBegin);
        String createTimeEnd = sdf.format(TimeEnd);
        //查询是否已有数据
        /*String createTimeBegin = "2018-01-25 00:00:00";
        String createTimeEnd = "2018-09-26 00:00:00";*/
        dataMap.put("dataDateBegin", createTimeBegin);
        dataMap.put("dataDateEnd", createTimeEnd);
        int hasCount = kwStatisticInterfaceService.getCount(dataMap);
        if (hasCount > 0) {
            logger.error("数据已存在==>currentDate:{}", currentDate);
            return;
        }
        filterMap.put("createTimeBegin", "'" + createTimeBegin + "'");
        filterMap.put("createTimeEnd", "'" + createTimeEnd + "'");
        pushMap.put("createTimeBegin", "'" + createTimeBegin + "'");
        pushMap.put("createTimeEnd", "'" + createTimeEnd + "'");
        limitMap.put("createTimeBegin", createTimeBegin);
        limitMap.put("createTimeEnd", createTimeEnd);
        List<KwInterfaceConfig> channelList = kwInterfaceConfigService.getModel(map);
        A:
        for (KwInterfaceConfig kwInterfaceConfig : channelList) {
            if (StringUtils.isBlank(kwInterfaceConfig.getCoreName())) {
                continue A;
            }
            List<Map<String, Object>> filterNumList = new ArrayList<>();
            List<Map<String, Object>> filterReasonList = new ArrayList<>();
            List<Map<String, Object>> pushReasonList = new ArrayList<>();
            Integer pushNum = 0;
            Integer pushrefuseNum = 0;
            Integer limitNum = 0;
            String channelName = kwInterfaceConfig.getInterfaceName();
            String channelCode = kwInterfaceConfig.getInterfaceCode();
            String coreName = kwInterfaceConfig.getCoreName();
            filterMap.put("table", "kw_" + coreName + "_filter");
            filterMap.put("channelCode", "'" + channelCode + "'");
            pushMap.put("table", "kw_" + coreName + "_push");
            pushMap.put("interfaceCode", "'" + channelCode + "'");
            limitMap.put("interfaceCode", channelCode);
            filterNumList = kwStatisticInterfaceService.getFilterNum(filterMap);
            if (filterNumList.size() != 0 && filterNumList != null) {
                filterReasonList = kwStatisticInterfaceService.getReasonFilter(filterMap);
                pushNum = kwStatisticInterfaceService.getNumPush(pushMap);
                pushrefuseNum = kwStatisticInterfaceService.getRefusNumPush(pushMap);
                pushReasonList = kwStatisticInterfaceService.getReasonPush(pushMap);
                KwStatisticInterface kwStatisticInterface = new KwStatisticInterface();
                kwStatisticInterface.setCreateDate(new Date());
                kwStatisticInterface.setDataDate(TimeBegin);
                kwStatisticInterface.setInterfaceCode(channelCode);
                kwStatisticInterface.setInterfaceName(channelName);
                Integer totalcount = 0;
                for (Map<String, Object> fMap : filterNumList) {
                    String flag = fMap.get("suited").toString();
                    String count = fMap.get("count").toString();
                    Integer countNum = Integer.valueOf(count);
                    totalcount += countNum;
                    if (flag.equals("Y")) {
                        kwStatisticInterface.setConformNum(Integer.valueOf(countNum));
                    } else if (flag.equals("N")) {
                        kwStatisticInterface.setInconformNum(Integer.valueOf(countNum));
                    }

                }
                kwStatisticInterface.setFilterNum(totalcount);
                kwStatisticInterface.setPushFailNum(pushrefuseNum);
                kwStatisticInterface.setPushSuccessNum(pushNum);
                kwStatisticInterface.setPushNum(pushrefuseNum + pushNum);
                Map<String, String> filterList = new HashMap<>();
                for (Map<String, Object> codeMap : filterReasonList) {
                    if (StringUtils.isNotBlank(codeMap.get("code").toString())) {
                        filterList.put(UserChannelEnum.getName((Integer) codeMap.get("code")), codeMap.get("totalcount").toString());
                    } else {
                        filterList.put("", codeMap.get("totalcount").toString());
                    }
                }
                kwStatisticInterface.setInconformReason(filterList.toString());
                Map<String, String> pushReasonMap = new HashMap<>();
                for (Map<String, Object> pMap : pushReasonList) {
                    if (StringUtils.isNotBlank((String) pMap.get("message"))) {
                        pushReasonMap.put("^" + pMap.get("message").toString(), pMap.get("pushcount").toString());
                    } else {
                        pushReasonMap.put("^", pMap.get("pushcount").toString());
                    }
                }
                String str = pushReasonMap.toString();
                kwStatisticInterface.setPushFailReason(str);

                limitNum = kwInterfaceLimitService.getLimitNum(limitMap);
                if (limitNum != null) {
                    if (limitNum.intValue() == pushNum.intValue()) {
                        kwStatisticInterface.setKeepWithLimit("Y");
                    } else {
                        kwStatisticInterface.setKeepWithLimit("N");
                    }
                }
                //针对回调获取电话号类接口单独处理
                //来凹渠道
                if ("laiao".equals(channelCode) || "haluo".equals(channelCode)) {
                    kwStatisticInterface.setPushSuccessNum(limitNum);
                    kwStatisticInterface.setKeepWithLimit("Y");
                }
                kwStatisticInterfaceService.insert(kwStatisticInterface);
            }
        }
    }


    /**
     * 月度统计
     *
     * @param dataDateBegin
     * @param dataDateEnd
     * @throws Exception
     */
    @Override
    public void statistics(String dataDateBegin, String dataDateEnd) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("dataDateBegin", dataDateBegin);
        map.put("dataDateEnd", dataDateEnd);
        List<Map<String, Object>> resultMap = kwStatisticInterfaceDao.getByMonth(map);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (resultMap.size() > 0) {
            for (Map<String, Object> param : resultMap) {
                KwStatisticInterfaceMonth kwStatisticInterface = new KwStatisticInterfaceMonth();
                kwStatisticInterface.setDataDate(sdf.parse(dataDateEnd));
                kwStatisticInterface.setInterfaceCode(param.get("interface_code").toString());
                kwStatisticInterface.setInterfaceName(param.get("interface_name").toString());
                kwStatisticInterface.setFilterNum(Integer.valueOf(param.get("totalFilterNum").toString()));
                kwStatisticInterface.setConformNum(Integer.valueOf(param.get("totalConForm").toString()));
                if (param.get("totalInNum") != null) {
                    kwStatisticInterface.setInconformNum(Integer.valueOf(param.get("totalInNum").toString()));
                } else {
                    kwStatisticInterface.setInconformNum(0);
                }
                kwStatisticInterface.setPushNum(Integer.valueOf(param.get("totalNum").toString()));
                kwStatisticInterface.setPushSuccessNum(Integer.valueOf(param.get("totalSuccessNum").toString()));
                kwStatisticInterface.setPushFailNum(Integer.valueOf(param.get("totalFailNum").toString()));
                kwStatisticInterfaceMonthService.insert(kwStatisticInterface);
            }
        }
    }


    @Override
    public void statisInterfaceByCode(String dataDate, String interfaceCode) throws Exception {
        Map<String, String> filterMap = new HashMap<>();
        Map<String, String> limitMap = new HashMap<>();
        Map<String, String> pushMap = new HashMap<>();
        Map<String, String> dataMap = new HashMap<>();
        Map<String, String> map = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date currentDate = com.meirengu.utils.DateUtils.getDate(dataDate, "yyyy-MM-dd");
        Date dayBeginTime = com.meirengu.utils.DateUtils.getDayBeginTime(currentDate);
        //当天结束时间
        Date dayEndTime = com.meirengu.utils.DateUtils.getDayEndTime(currentDate);
        String createTimeBegin = sdf.format(dayBeginTime);
        String createTimeEnd = sdf.format(dayEndTime);
        dataMap.put("dataDateBegin", createTimeBegin);
        dataMap.put("dataDateEnd", createTimeEnd);
        dataMap.put("interfaceCode", interfaceCode);
        int hasCount = kwStatisticInterfaceService.getCount(dataMap);
        if (hasCount > 0) {
            logger.error("数据已存在==>currentDate:{}", currentDate);
            return;
        }
        filterMap.put("createTimeBegin", "'" + createTimeBegin + "'");
        filterMap.put("createTimeEnd", "'" + createTimeEnd + "'");
        pushMap.put("createTimeBegin", "'" + createTimeBegin + "'");
        pushMap.put("createTimeEnd", "'" + createTimeEnd + "'");
        limitMap.put("createTimeBegin", createTimeBegin);
        limitMap.put("createTimeEnd", createTimeEnd);
        List<KwInterfaceConfig> channelList = kwInterfaceConfigService.getModel(map);
        A:
        for (KwInterfaceConfig kwInterfaceConfig : channelList) {
            if (StringUtils.isBlank(kwInterfaceConfig.getCoreName())) {
                continue A;
            }
            if (!(kwInterfaceConfig.getInterfaceCode().equals(interfaceCode))) {
                continue A;
            }
            List<Map<String, Object>> filterNumList = new ArrayList<>();
            List<Map<String, Object>> filterReasonList = new ArrayList<>();
            List<Map<String, Object>> pushReasonList = new ArrayList<>();
            Integer pushNum = 0;
            Integer pushrefuseNum = 0;
            Integer limitNum = 0;
            String channelName = kwInterfaceConfig.getInterfaceName();
            String channelCode = kwInterfaceConfig.getInterfaceCode();
            String coreName = kwInterfaceConfig.getCoreName();
            filterMap.put("table", "kw_" + coreName + "_filter");
            filterMap.put("channelCode", "'" + channelCode + "'");
            pushMap.put("table", "kw_" + coreName + "_push");
            pushMap.put("interfaceCode", "'" + channelCode + "'");
            limitMap.put("interfaceCode", channelCode);
            filterNumList = kwStatisticInterfaceService.getFilterNum(filterMap);
            if (filterNumList.size() != 0 && filterNumList != null) {
                filterReasonList = kwStatisticInterfaceService.getReasonFilter(filterMap);
                pushNum = kwStatisticInterfaceService.getNumPush(pushMap);
                pushrefuseNum = kwStatisticInterfaceService.getRefusNumPush(pushMap);
                pushReasonList = kwStatisticInterfaceService.getReasonPush(pushMap);
                KwStatisticInterface kwStatisticInterface = new KwStatisticInterface();
                kwStatisticInterface.setCreateDate(new Date());
                kwStatisticInterface.setDataDate(dayBeginTime);
                kwStatisticInterface.setInterfaceCode(channelCode);
                kwStatisticInterface.setInterfaceName(channelName);
                Integer totalcount = 0;
                for (Map<String, Object> fMap : filterNumList) {
                    String flag = fMap.get("suited").toString();
                    String count = fMap.get("count").toString();
                    Integer countNum = Integer.valueOf(count);
                    totalcount += countNum;
                    if (flag.equals("Y")) {
                        kwStatisticInterface.setConformNum(Integer.valueOf(countNum));
                    } else if (flag.equals("N")) {
                        kwStatisticInterface.setInconformNum(Integer.valueOf(countNum));
                    }

                }
                kwStatisticInterface.setFilterNum(totalcount);
                kwStatisticInterface.setPushFailNum(pushrefuseNum);
                kwStatisticInterface.setPushSuccessNum(pushNum);
                kwStatisticInterface.setPushNum(pushrefuseNum + pushNum);
                Map<String, String> filterList = new HashMap<>();
                for (Map<String, Object> codeMap : filterReasonList) {
                    if (StringUtils.isNotBlank(codeMap.get("code").toString())) {
                        filterList.put(UserChannelEnum.getName((Integer) codeMap.get("code")), codeMap.get("totalcount").toString());
                    } else {
                        filterList.put("", codeMap.get("totalcount").toString());
                    }
                }
                kwStatisticInterface.setInconformReason(filterList.toString());
                Map<String, String> pushReasonMap = new HashMap<>();
                for (Map<String, Object> pMap : pushReasonList) {
                    if (StringUtils.isNotBlank((String) pMap.get("message"))) {
                        pushReasonMap.put("^" + pMap.get("message").toString(), pMap.get("pushcount").toString());
                    } else {
                        pushReasonMap.put("^", pMap.get("pushcount").toString());
                    }
                }
                String str = pushReasonMap.toString();
                kwStatisticInterface.setPushFailReason(str);

                limitNum = kwInterfaceLimitService.getLimitNum(limitMap);
                if (limitNum != null) {
                    if (limitNum.intValue() == pushNum.intValue()) {
                        kwStatisticInterface.setKeepWithLimit("Y");
                    } else {
                        kwStatisticInterface.setKeepWithLimit("N");
                    }
                }
                //针对回调获取电话号类接口单独处理
                //来凹渠道
                if ("laiao".equals(channelCode)) {
                    kwStatisticInterface.setPushSuccessNum(limitNum);
                    kwStatisticInterface.setKeepWithLimit("Y");
                }
                kwStatisticInterfaceService.insert(kwStatisticInterface);
            }
        }
    }


    /**
     * 统计当月数据
     *
     * @param dataDateBegin
     * @param dataDateEnd
     * @throws Exception
     */
    @Override
    public void monthStatistics(String dataDateBegin, String dataDateEnd) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("dataDateBegin", dataDateBegin);
        map.put("dataDateEnd", dataDateEnd);
        List<Map<String, Object>> resultMap = kwStatisticInterfaceDao.getByMonth(map);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (resultMap.size() > 0) {
            for (Map<String, Object> param : resultMap) {
                String interfaceCode = param.get("interfaceCode").toString();
                map.put("interfaceCode", interfaceCode);
                List<KwStatisticInterfaceMonth> modelList = kwStatisticInterfaceMonthService.getModel(map);
                KwStatisticInterfaceMonth kwStatisticInterface = new KwStatisticInterfaceMonth();
                kwStatisticInterface.setDataDate(sdf.parse(dataDateEnd));
                kwStatisticInterface.setInterfaceCode(param.get("interfaceCode").toString());
                kwStatisticInterface.setInterfaceName(param.get("interfaceName").toString());
                kwStatisticInterface.setFilterNum(Integer.valueOf(param.get("totalFilterNum").toString()));
                kwStatisticInterface.setConformNum(Integer.valueOf(param.get("totalConForm").toString()));
                if (param.get("totalInNum") != null) {
                    kwStatisticInterface.setInconformNum(Integer.valueOf(param.get("totalInNum").toString()));
                } else {
                    kwStatisticInterface.setInconformNum(0);
                }
                kwStatisticInterface.setPushNum(Integer.valueOf(param.get("totalNum").toString()));
                kwStatisticInterface.setPushSuccessNum(Integer.valueOf(param.get("totalSuccessNum").toString()));
                kwStatisticInterface.setPushFailNum(Integer.valueOf(param.get("totalFailNum").toString()));
                if (modelList.size() > 0) {
                    kwStatisticInterface.setId(modelList.get(0).getId());
                    kwStatisticInterfaceMonthService.update(kwStatisticInterface);
                } else if (modelList.size() == 0) {
                    kwStatisticInterfaceMonthService.insert(kwStatisticInterface);
                } else {
                    throw new Exception("月度统计数据异常");
                }

            }
        }
    }


}
